<template>
    <div v-if="designer.formType === 'render'">
        <slot></slot>
    </div>
    <div v-else :class="selectWidgetId == widgetId ? 'select' : ''" class="widget" @click.stop="selectWidget">
        <el-button v-if="selectWidgetId == widgetId" class="delete-icon" @click.stop="removeWidget" type="danger"
            :icon="DeleteFilled" circle size="small" />

        <div class="heard" v-if="selectWidgetId == widgetId">
            <slot name="heard"></slot>
        </div>
        <slot></slot>
        <div class="bottom" v-if="selectWidgetId == widgetId">
            <slot name="bottom"></slot>
        </div>
        <slot name="footer" v-if="selectWidgetId == widgetId"></slot>
    </div>
</template>

<script setup>
import { inject, ref } from 'vue'
import { DeleteFilled } from '@element-plus/icons-vue'

const designer = inject('designer');
const widgetList = inject('widgetList')
const selectWidgetId = inject('selectWidgetId', ref(null))

const props = defineProps({
    widgetId: {
        type: String,
        required: true,
        default: ''
    },
})

const selectWidget = () => {
    selectWidgetId.value = props.widgetId
}

// 删除当前组件
const removeWidget = () => {
    if (widgetList.value) {
        removeById(widgetList.value, props.widgetId);
    }
};

const removeById = (list, id) => {
    for (let i = list.length - 1; i >= 0; i--) {
        const item = list[i];
        if (item.id === id) {
            list.splice(i, 1);
            return true;
        } else if (item.children && item.children.length > 0) {
            const removed = removeById(item.children, id);
            if (removed) return true;
        }
    }
    return false;
};
</script>

<style scoped>
.widget {
    position: relative;
}

.select {
    border: 1px dashed #409EFF;
}

.heard {
    position: absolute;
    top: 3px;
    left: 5px;
    cursor: pointer;
    z-index: 9;
}

.bottom {
    position: absolute;
    bottom: 3px;
    left: 5px;
    cursor: pointer;
    z-index: 9;
}

.delete-icon {
    position: absolute;
    bottom: 3px;
    right: 3px;
    cursor: pointer;
    z-index: 9;
}
</style>